import Order, { IOrder } from "../../models/Order";
import Product from "../../models/Product";
import BlindBox from "../../models/BlindBox";
import Member from "../../models/Member";
import moment from "moment";
import _ from "lodash";
import mongoose from "mongoose";
import alipaySdk from "alipay-sdk";
import { handleLottery } from '../OrderController'
//@ts-ignore
// import Payment from 'wxpay-v3'
import WxPay from 'wechatpay-node-v3';
import fs from 'fs'
import path from 'path'
import request from 'superagent';
import axios from "axios";
import { tr } from "@faker-js/faker";

const alipaySDK = new alipaySdk({
    appId: "2021004130661796",
    signType: "RSA2",
    // gateway: "https://openapi.alipaydev.com/gateway.do",
    privateKey:
        "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDQ4TEioaEwmgc3UgRxzBvtqzDKsU8yH+wWSLMzoalNXYHuMa0aZNwWBTYjbuizSWgrzdREnUzevgp5fHFLgVJi9xu3geNm0R0XKJ+wBJ5vJFTfEIytBElvTBa4MjYLTgFK/OoR0uW30SViGkbrGnd3N/2vFVNqJiLv9aTg6VJPaIp5ld7HkoPcyDZHRdOBZyXLnAbQzYvK6oHolZMbInsWNGGLp9AdyZEApVEYroCAyWUhe4lq+R1lfSGoIlVCb+YhR1qjaPlVA5/zF3Jlb2vg+MlZnncJQWMKn9ZvGWuFSCilLUFf4R9X7ySgSXuo6DDF+DUz8ScQbXAxk4C8tzv1AgMBAAECggEAbgqU9iesYYxjzNMaoFDlTbpoRABRNpj2qW63abX7GVTvxGrLRSJph/hK4zPkx78ecCVJdLRh8N6xafsTPLHuk1CXe3+kK2BzMOYn6nUkemzrgXCYi/W8MjQlq/hX3HDF4ZmIPseaWdKHHT22qtkQovAOZ5SWk09wDHae3BZPVKFMpyJwS/NGh8TiTLNLXGOq1PN6eyEFqyBxB5IJ4ro53RIJhUmjpoOLLBxdCjFTiP00tUY2S00IKrxa83hItRqM7PYavxUdy2SS97VAil4KOqU59BAMbEk7jNFhhYJ+VQzU8f86tVzOgzqZTRusKPvrDcHEtnYjdsM/hghpuuAOKQKBgQDw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f9rxVTaiYi7/Wk4OlST2iKeZXex5KD3Mg2R0XTgWcly5wG0M2LyuqB6JWTGyJ7FjRhi6fQHcmRAKVRGK6AgMllIXuJavkdZX0hqCJVQm/mIUdao2j5VQOf8xdyZW9r4PjJWZ53CUFjCp/WbxlrhUgopS1BX+EfV+8koEl7qOgwxfg1M/EnEG1wMZOAvLc79QIDAQAB",
});

// console.log('path::::', path.resolve(__dirname, './wx_key.pem'))
// const wxCert = fs.readFileSync(path.resolve(__dirname, './wx_cert.pem'));
// const wxKey = fs.readFileSync(path.resolve(__dirname, './wx_key.pem'));
// console.log('wx_key: ', privateKey)

const payOrderForProduct = async (req: any, res: any) => {
    try {
        console.log("支付参数：", req.body);
        const { orderId, payType, price, productName, quantity, remark, openId } = req.body;

        // 1. 查找订单并验证有效性
        const order = await Order.findById(orderId);
        console.log("查找订单并验证有效性:", order);
        if (!order) {
            return res.status(500).json({
                status: "false",
                message: "订单不存在",
                data: {
                    orderId,
                },
            });
        }

        const currentTime = moment(); // 当前时间
        const orderTime = moment(order.createdAt); // 订单创建时间
        const timeDifference = currentTime.diff(orderTime, "minutes"); // 计算时间差，单位分钟

        if (timeDifference > 30) {
            return res.status(500).json({
                status: "false",
                message: "订单已失效",
                data: {
                    orderId,
                },
            });
        }

        // 2. 查找商品并验证库存
        const product = await Product.findById(order.product.goodsId);
        console.log("查找商品并验证库存:", Product);
        if (!product) {
            return res.status(500).json({
                status: "false",
                message: "商品不存在",
                data: {
                    orderId,
                },
            });
        }

        if (product.stock - order.quantity < 0) {
            return res.status(500).json({
                status: "false",
                message: "商品库存不足",
                data: {
                    orderId,
                },
            });
        }


        // 3. 查找用户
        const member = await Member.findById(order.user);
        if (!member) {
            return res.status(500).json({
                status: "false",
                message: "用户不存在",
                data: {
                    orderId,
                },
            });
        }


        order.productType = 'product'
        // 4. 判断支付类型进行支付
        if (payType === "balance") {
            if ((member.balance || 0) < (order.quantity * product.needsBalance)) {
                return res.status(500).json({
                    status: "false",
                    message: "积分不足，无法购买",
                    data: {
                        orderId,
                    },
                });
            }

            // 使用用户积分支付、商品库存、订单状态
            // @ts-ignore
            member.balance -= (order.quantity * product.needsBalance);
            product.stock -= order.quantity;
            order.totalAmount = order.quantity * product.needsBalance
            order.status = "finished";
            // const { lotteryResults, hasWonAnyPrize } = await handleLottery(orderId)
            order.remark = `积分消费${order.quantity * product.needsBalance}`;
            order.payMethod = payType

            // 保存更新后的数据
            await member.save();
            await product.save();
            await order.save();

            res.json({
                status: "ok",
                message: "购买成功！",
                data: {
                    orderId,
                    payType
                    // lotteryResults,
                    // reward: hasWonAnyPrize,
                },
            });
        } else if (payType === "alipay") {
            const bizContent = {
                out_trade_no: orderId,
                total_amount: price,
                subject: productName,
                product_code: "QUICK_WAP_WAY",
                // product_code: "FAST_INSTANT_TRADE_PAY",
            }

            console.log('进行支付宝支付===========', bizContent)
            const result = await alipaySDK.pageExec("alipay.trade.wap.pay", {
                method: 'POST',
                bizContent,
                returnUrl: `https://www.channing-mall.cn/order/payResult?orderId=${orderId}&payResult=success&payType=alipay`,
                notifyUrl: `https://www.channing-mall.cn/order/payResult?orderId=${orderId}&payResult=success&payType=alipay`
            });


            if (result) {
                // 保存更新后的数据
                //给用户积分
                // member.balance = Number(member.balance) + Math.floor(price / 10)
                // await member.save();
                // await product.save();
                order.payMethod = payType
                await order.save();

                console.log('返回 result:', result)

                res.json({
                    status: "ok",
                    message: "支付成功！",
                    data: {
                        url: result,
                        payType
                    },
                });
            }
        } else if (payType === "wechat-pay") {
            console.log('发起微信支付')
            order.payMethod = payType

            const payment = new WxPay({
                appid: 'wx2fd1ab3a67fad2d3',
                mchid: '1668468944',
                publicKey: fs.readFileSync(path.resolve(__dirname, './wx_cert.pem')), // 公钥
                privateKey: fs.readFileSync(path.resolve(__dirname, './wx_key.pem')), // 秘钥
            });

            const userAgent = req.headers['user-agent'].toLowerCase();
            //判断是否在微信浏览器内打开
            if (userAgent.includes('micromessenger')) {
                // const $appId = ''
                // const $redirectUrl = 'http://localhost:2023/order/payPage?orderId=660e373e8e69127eea1892a5&productType=product'
                // const $responseType = 'code'
                // const $scope = 'snsapi_base'
                // const $state = ''
                // const codeResult = await axios.post(`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${$appId}&redirect_uri=${$redirectUrl}&response_type=${$responseType}&scope=${$scope}&state=${$state}#wechat_redirect`)
                // if (codeResult) {
                //     console.log('codeResult:', codeResult)
                // }
                try {
                    const params = {
                        description: `${productName}`,
                        out_trade_no: orderId,
                        notify_url: 'https://www.channing-mall.cn/api/order/notify_wx_product',
                        amount: {
                            total: price * 100,
                            currency: 'CNY'
                        },
                        payer: {
                            openid: openId
                        },
                        scene_info: {
                            payer_client_ip: req.ip,
                        },
                    }
                    const result: any = await payment.transactions_jsapi(params)
                    if (result) {
                        console.log('result:', result)

                        res.json({
                            status: "ok",
                            message: "唤起微信支付",
                            data: {
                                appId: result.appId,
                                timeStamp: result.timeStamp,
                                nonceStr: result.nonceStr,
                                packageStr: result.package,
                                signType: result.signType,
                                paySign: result.paySign
                            },

                        });
                    }
                } catch (error: any) {
                    console.error('Error during payment request:', error.response?.data || error.message);
                    res.status(500).json({
                        status: "false",
                        message: error.response?.data || error.message,
                    });
                }

            } else {

                const params = {
                    appid: 'wxdd3e756f42838499',
                    mchid: '1668468944',
                    description: `${productName}`,
                    out_trade_no: orderId,
                    notify_url: 'https://www.channing-mall.cn/api/order/notify_wx_product',
                    amount: {
                        total: price * 100,
                        currency: 'CNY'
                    },
                    scene_info: {
                        payer_client_ip: req.ip,
                        h5_info: {
                            type: 'Wap',
                            // app_name: 'Chaning商城',
                            // app_url: 'https://www.channing-mall.cn',
                        },
                    },
                };

                const nonce_str = Math.random().toString(36).substr(2, 15), // 随机字符串
                    timestamp = parseInt(+new Date() / 1000 + '').toString(), // 时间戳 秒
                    url = '/v3/pay/transactions/h5';

                // 获取签名
                const signature = payment.getSignature('POST', nonce_str, timestamp, url, params); // 如果是get 请求 则不需要params 参数拼接在url上 例如 /v3/pay/transactions/id/12177525012014?mchid=1230000109
                // 获取头部authorization 参数
                const authorization = payment.getAuthorization(nonce_str, timestamp, signature);
                try {
                    const result = await axios.post('https://api.mch.weixin.qq.com/v3/pay/transactions/h5', params, {
                        headers: {
                            'Accept': 'application/json',
                            'Content-Type': 'application/json',
                            'User-Agent': req.headers['user-agent'],
                            Authorization: authorization,
                        }
                    });
                    // console.log('result==========>', result);

                    const redirectUrl = `redirect_url=https://www.channing-mall.cn/order/payResult?oderId=${orderId}&payResult=success&payType=wechat-pay`
                    // console.log('result==========>', result);
                    console.log('url==========>', result.data.h5_url + encodeURIComponent(redirectUrl));
                    order.save()
                    res.json({
                        status: "ok",
                        message: "唤起微信支付",
                        data: {
                            // url: result.data.h5_url,
                            url: result.data.h5_url + '&' + encodeURIComponent(redirectUrl),
                            payType
                        },
                    });
                } catch (error: any) {
                    console.error('Error during payment request:', error.response?.data || error.message);
                    res.status(500).json({
                        status: "false",
                        message: error.response?.data || error.message,
                    });
                }
            }

        }

        // res.status(500).json({
        //     status: "false",
        //     message: "支付失败！",
        //     data: null,
        // });
    } catch (error: any) {
        console.error('支付失败:', error.message)
        res.status(500).json({
            status: "false",
            message: "支付失败！",
            data: error.message,
        });
    }
};

export default payOrderForProduct